<template>
    <el-dialog :modal=false :visible.sync="uploadDialogVisible" v-dialogDrag
               :close-on-click-modal="false" title="上传到" id="uploadDialog">
        <el-tree style="padding-bottom:10px;overflow-y: auto;height: 200px"
                 ref="DirectoryTree"
                 highlight-current
                 :data="data"
                 :props="defaultProps"
                 lazy
                 :load="loadData"
                 accordion
                 :check-on-click-node="true"
                 @node-click="handleNodeClick">
        </el-tree>
        <el-upload
                id="uploadData"
                class="upload"
                ref="fileUpload"
                action=""
                multiple
                :on-change="handleChange"
                :auto-upload="false"
                :on-remove="handleDelete"
                :file-list="fileList"
                :before-upload="beforeUpload"
                style="height: 150px;">
            <!--:show-file-list="false"-->
            <el-button size="small" type="primary" style="margin: 20px 0 0 ">选取数据</el-button>
        </el-upload>
        <el-button @click="confirmAdd" type="primary" v-loading.lock="isLoading">确定</el-button>
        <el-button @click="cancle" type="primary">取消</el-button>
    </el-dialog>
</template>
<script>

    export default {

        data() {
            return {
                uploadDialogVisible: false,
                data: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                fileList: [],
                currentNode: '',
                isLoading: false,
                pathParam: "",
                uploadRate: 0.0,
                stringRate: '0.00%'
            };
        },
        methods: {
            beforeUpload:function(file) {
                //todo 前端验证文件大小，问题是为什么不进入这个函数
                // alert("gfgf")
                // console.log(file)
               // let testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
               //  const extension = testmsg === 'xls'
               //  const extension2 = testmsg === 'xlsx'
               //  const isLt2M = file.size / 1024 / 1024 < 10
               //  if(!extension && !extension2) {
               //      this.$message({
               //          message: '上传文件只能是 xls、xlsx格式!',
               //          type: 'warning'
               //      });
               //  }
               //  if(!isLt2M) {
               //      this.$message({
               //          message: '上传文件大小不能超过 10MB!',
               //          type: 'warning'
               //      });
               //  }
               //  return extension || extension2 && isLt2M
               //  let filesize = false;
               //  if(!filesize) {
               //           this.$message({
               //               message: '上传文件大小不能超过200MB!',
               //               type: 'warning'
               //           });
               //       }
               //  return filesize
            },
            //上传成功或失败都会触发
            handleChange(file, fileList) {
                this.fileList = fileList;
                console.log(file.raw);
            },
            handleDelete(file, fileList) {
                console.log(fileList);
                this.fileList = fileList;
            },
            confirmAdd(file, fileList) {
                this.$refs.fileUpload.submit();
                let that = this;
                let node = this.currentNode;
                this.pathParam = "";
                if (node == "" || node.level === 0) {
                    this.pathParam = "/";
                } else {
                    for (let i = 0; i < this.currentNode.level; i++) {
                        this.pathParam = "/" + node.label + this.pathParam;
                        node = node.parent;
                    }
                }
                if (this.pathParam && this.fileList.length) {
                    let loading = this.$loading({
                        lock: true,
                        // text: '文件上传中...',
                        text: '文件上传中, 已完成 ' + that.stringRate + ' .',
                        target: "#uploadDiv",
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    let fileData = new FormData();
                    for (let i = 0; i < this.fileList.length; i++) {
                        fileData.append('file', this.fileList[i].raw);
                    }
                    // fileData.append('path', this.pathParam);
                    // let url = "http://localhost:9000/dbfg/userself/upload";
                    // let url = "http://192.168.1.5:9000/dbfg/userSpace/upload?path=" + this.pathParam;
                    let config = {   // 用于需要显示上传进度的post请求配置参数
                        headers: { 'Content-Type': 'multipart/form-data' },
                        onUploadProgress: function (e) {
                            // 属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
                            // 如果lengthComputable为false，就获取不到e.total和e.loaded
                            if (e.lengthComputable) {
                                let rate = that.uploadRate = e.loaded / e.total;  //已上传的比例
                                if (rate < 1) {
                                    // 这里的进度只能表明文件已经上传到后台，但是后台有没有处理完还不知道
                                    // 因此不能直接显示为100%，不然用户会误以为已经上传完毕，关掉浏览器的话就可能导致上传失败
                                    // 等响应回来时，再将进度设为100%
                                    that.uploadRate = rate;
                                    that.stringRate = (rate * 100).toFixed(2) + '%';
                                    loading.text = '文件上传中, 已完成 ' + that.stringRate + ' .';
                                }
                            }
                        }
                    };


                    this.$axios.postAdvanced(that.$URL.fileUploadUrl+that.pathParam, fileData, config)
                        .then(function (res) {

                            // 后台完成数据接收, 此时设置进度为100%
                            that.uploadRate = 1.0;
                            that.stringRate = '100.00%';
                            loading.text = '文件上传中, 已完成 ' + that.stringRate + ' .';

                            loading.close();
                            if (res.code === 200) {
                                that.$message({
                                    message: '文件上传成功',
                                    type: 'success'
                                });
                                //刷新目录
                                that.$emit('refreshCurrentTable');
                                //上传成功时传递一个值给图表工程，进行图表工程数据选择树的刷新
                                that.uploadDialogVisible = false;
                                // 重置进度
                                that.uploadRate = 0.0;
                                that.stringRate = '0.00%';

                            } else {
                                that.$message({
                                    message: '文件上传失败:' + res.message,
                                    type: 'warning'
                                });
                            }
                            that.uploadDialogVisible = false;
                            // 重置进度
                            that.uploadRate = 0.0;
                            that.stringRate = '0.00%';

                        }).catch(function (error) {
                        loading.close();
                        that.uploadDialogVisible = false;
                        console.log(error);
                    });
                    this.fileList = [];
                } else {
                    this.$message.warning(`请正确选择上传路径和上传文件!`);
                }
            },
            handleNodeClick(data, node) {
                this.currentNode = node;
                // console.log(data);
                // console.log(node)
            },
            loadData(node, resolve) {
                let that = this;
                let data = [];
                let currentNode = node;
                let path = "";
                if (node.data.type === "File") {
                    return resolve([]);
                }
                if (node.level === 0) {
                    path = "/";
                } else {
                    for (let i = 0; i < node.level; i++) {
                        path = "/" + currentNode.label + path;
                        currentNode = currentNode.parent;
                    }
                }
                // let url = "http://192.168.1.5:9000/dbfg/userSpace/all?path=";
                this.$axios.get(that.$URL.fileGetUrl + path)
                    .then(function (res) {
                        if (res.code == 200) {
                            for (let item of res.body) {
                                if (item.Type != "File") {
                                    let file = {};
                                    file.label = item.Name;
                                    file.type = item.Type;
                                    file.children = [""];
                                    data.push(file);
                                }
                            }
                            return resolve(data);
                        } else {
                            return resolve([]);
                        }
                    });
            },
            refresh() {
                this.fileList = [];
                this.pathParam = "";
                this.currentNode = '';
                let that = this;
                let data = [];
                // this.$axios.get(that.$URL.userSpaceAllFileUrl + "/")
                //     .then(function (res) {
                //         if (res.code == 200) {
                //             for (let item of res.body) {
                //                 if (item.Type != 'File') {
                //                     let file = {};
                //                     file.label = item.Name;
                //                     file.type = item.Type;
                //                     file.children = [""];
                //                     file.id = item.Name + "_" + new Date().getTime();
                //                     data.push(file);
                //                 }
                //             }
                //             that.data = data;
                //         }
                //     });
            },
            cancle() {
                this.uploadDialogVisible = false;
                this.fileList = [];
            }
        },
        created() {
            let that = this;
            this.$Bus.$on("uploadDialogVisible", res => {
                that.uploadDialogVisible = res.visible;
            })
        }
    }
</script>

<style >
    #uploadDialog .el-dialog__body {
        padding: 20px 20px;
        color: #606266;
        font-size: 14px;
        word-break: break-all;
    }
    #uploadDialog input[type=file] {
        display: none;
    }

    #uploadData .el-upload-list{
        padding: 0 0 10px 0;
        overflow: auto;
        height: 100px;
    }
</style>